package easier.window.dialog;

import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.DialogFragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;

/**
 * 创建一个规范:
 * 1.创建dialog
 * 2.设置dialog布局
 */
public class BaseDialogFragment extends DialogFragment {

    /**
     * 标记是否正在显示
     */
    private boolean isShowing;

    /**
     * dialog布局
     */
    private View mDialogView;

    @NonNull
    @Override
    public Dialog onCreateDialog( @Nullable Bundle savedInstanceState ) {

        Context context = getContext();
        assert context != null;

        Dialog dialog = createDialog( context, savedInstanceState );
        if ( mDialogView != null ) {
            dialog.setContentView( mDialogView, generateLayoutParams() );
        }

        return dialog;
    }

    /**
     * @return 创建dialog
     */
    protected Dialog createDialog( Context context, @Nullable Bundle savedInstanceState ) {

        return new BaseDialog( context );
    }

    /**
     * @param dialogView 创建布局,需要在{@link BaseDialogFragment}创建之后就调用
     */
    public void setDialogView( View dialogView ) {

        mDialogView = dialogView;
    }

    public ViewGroup.LayoutParams generateLayoutParams() {

        return new LayoutParams( LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT );
    }

    public View getDialogView() {

        return mDialogView;
    }

    @Override
    public void show( @NonNull FragmentManager manager, @Nullable String tag ) {

        isShowing = true;
        super.show( manager, tag );
    }

    @Override
    public int show( @NonNull FragmentTransaction transaction, @Nullable String tag ) {

        isShowing = true;
        return super.show( transaction, tag );
    }

    @Override
    public void showNow( @NonNull FragmentManager manager, @Nullable String tag ) {

        isShowing = true;
        super.showNow( manager, tag );
    }

    @Override
    public void onDismiss( @NonNull DialogInterface dialog ) {

        isShowing = false;
        super.onDismiss( dialog );
    }

    @Override
    public void onCancel( @NonNull DialogInterface dialog ) {

        isShowing = false;
        super.onCancel( dialog );
    }

    public boolean isShowing() {

        return isShowing;
    }
}